package com.conduit.comnands;

import java.awt.Robot;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

import org.sikuli.script.AppearEvent;
import org.sikuli.script.ChangeEvent;
import org.sikuli.script.Region;
import org.sikuli.script.Screen;
import org.sikuli.script.SikuliEventObserver;
import org.sikuli.script.SikuliScript;
import org.sikuli.script.VanishEvent;

import com.conduit.agent.Main;
import com.conduit.commands.prototype.AbstractCommand;
import com.conduit.enums.ResultCode;

public class SikuliStartScreenCapturingCommand extends AbstractCommand {
	private Screen s;

	public SikuliStartScreenCapturingCommand() {
		commandSyntax = "start screen capturing";

	}

	@Override
	@SuppressWarnings("deprecation")
	public void executeWithArgs(String args) {

		// final Region r = new Region(770, 635, 510, 390);
		try {
			// final SikuliScript scrpt = new SikuliScript();
			final Robot robot = new Robot();

			setResult("Sikuli Started Capturing the Screen");
			setResultCode(ResultCode.Successes);

			s.onChange(new SikuliEventObserver() {
				int i = 1;

				@Override
				public void targetAppeared(AppearEvent arg0) {
				}

				@Override
				public void targetChanged(ChangeEvent arg0) {
					try {
						if (s.find("c:\\jenkins\\av.png") != null) {
							BufferedImage image = robot.createScreenCapture(s
									.getRect());

							ImageIO.write(image, "png", new File("capture" + i
									+ ".png"));
							i++;
							System.out.println(String.format(
									"%s, %s, %s, %s",
									Main.getMachineIp(), "A Screenshoot was Taken" ,
									"captrue"+i+".png", ResultCode.Warning.getResult()));
						}
					} catch (Exception e) {
					}
				}

				@Override
				public void targetVanished(VanishEvent arg0) {
				}
			});

			// start the observation...
			s.observeInBackground(Long.MAX_VALUE);

		} catch (Exception e) {
			setResult("Sikuli Could not Capture the Screen");
			setResultCode(ResultCode.Error);
		}
	}

	public static void main(String[] args) {
		new SikuliStartScreenCapturingCommand().executeWithArgs("");
	}

	@Override
	public String getCommandName() {
		// TODO Auto-generated method stub
		return "Strat Screen Capturing";
	}

	public Screen getS() {
		return s;
	}

	public void setS(Screen s) {
		this.s = s;
	}

}
